package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.dtos.HistorySearchDto;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.SearchHistoryService;
import com.heima.utils.thread.AppThreadLocalUtil;
import com.heima.utils.thread.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jack
 * @data 2024 11:45
 */
@Service
@Slf4j
public class SearchHistoryServiceImpl implements SearchHistoryService {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Async
    public void saveHistory(String keyWord,Integer userId) {
        //1. 将搜索关键字封装成ApUserSearch
        ApUserSearch search = new ApUserSearch();
        search.setKeyword(keyWord);
        search.setUserId(userId);
        search.setCreatedTime(new Date());

        //2. 查询当前用户是否搜索过当前的关键字
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyWord));
        ApUserSearch searchInMongo = mongoTemplate.findOne(query, ApUserSearch.class);

        //3. 搜过：更新历史记录的时间为最新时间
        if (searchInMongo != null){
            searchInMongo.setCreatedTime(new Date());
            mongoTemplate.save(searchInMongo);
        }else {
            //4. 没搜过：先判断当前用户的记录数是否超过10
            Query query1 = Query.query(Criteria.where("userId").is(userId));
            List<ApUserSearch> list = mongoTemplate.find(query1, ApUserSearch.class);
            if (list == null || list.size() < 10){
                //5. 没超过：直接保存当前用户的搜索记录
                mongoTemplate.save(search);
            }else{
                //6. 超过：拿本次搜索的记录替换最旧的搜索记录
                list = list.stream().sorted(new Comparator<ApUserSearch>() {
                    @Override
                    public int compare(ApUserSearch o1, ApUserSearch o2) {
                        //按日期升序
                        return o1.getCreatedTime().compareTo(o2.getCreatedTime());
                    }
                }).collect(Collectors.toList());

                ApUserSearch searchOldest = list.get(0);
                searchOldest.setKeyword(keyWord);
                searchOldest.setCreatedTime(new Date());
                mongoTemplate.save(searchOldest);
            }
        }

    }

    /**
     * 加载用户搜索历史记录
     *
     * @return
     */
    @Override
    public ResponseResult load() {
        ApUser apUser = AppThreadLocalUtil.getUser();
        if (apUser == null || apUser.getId() == 0)
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);


        Query query = Query.query(Criteria
                .where("userId")
                .is(AppThreadLocalUtil.getUser().getId()))
                .with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> list = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(list);
    }

    @Override
    public ResponseResult delete(HistorySearchDto dto) {
        if(dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser apUser = AppThreadLocalUtil.getUser();
        if(apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        mongoTemplate.remove(Query.query(Criteria.where("userId").is(apUser.getId()).and("id").is(dto.getId())),ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
